package net.piggy.web.service;

import com.alibaba.fastjson.JSONObject;
import net.piggy.common.constant.ParameterConstant;
import net.piggy.common.util.general.UuidUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class SecurityService {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private AuthenticationManager authenticationManager;

    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,password);
        Authentication authenticate = authenticationManager.authenticate(token);
        Object object = authenticate.getPrincipal();
        String uuid = UuidUtil.getUuid();
        String jsonString = JSONObject.toJSONString(object);
        redisTemplate.opsForValue().set(ParameterConstant.TOKEN+uuid, jsonString,1, TimeUnit.HOURS);
        return uuid;
    }
}
